package com.example.reggie1.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie1.common.R;
import com.example.reggie1.entity.Employee;
import com.example.reggie1.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by jinkun.tian on 2023/3/23
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        // 1. 将pwd使用md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 2. 根据username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        // 3. 如果没查到，返回登录失败
        if(emp == null){
            return R.error("登录失败");
        }
        // 4. 如果不匹配，返回登录失败
        if(emp.getPassword().equals(password)){
            return R.error("登录失败");
        }
        // 5. 如果已禁用，返回账户已禁用
        if(emp.getStatus() == 0){
            return R.error("账户被禁用");
        }
        // 6. 登录成功，将员工ID存入Session中
        request.getSession().setAttribute("employee",emp.getId());
//        return "登录成功";
        return R.success(employee);
    }
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        Page pageInfo = new Page(page,pageSize);

        LambdaQueryWrapper<Employee> queryWrap = new LambdaQueryWrapper<>();

        queryWrap.like(StringUtils.isNotEmpty(name),Employee::getName,name);

        queryWrap.orderByDesc(Employee::getUpdateTime);

        employeeService.page(pageInfo,queryWrap);

        return R.success(pageInfo);
    }
    @GetMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }



}
